import React, { useState, useEffect, useRef } from 'react';
import { useNavigate } from 'react-router-dom';
import { 
  UserContactOutline,
  QuestionCircleOutline,
  MailOutline,
  FileOutline,
  ContentOutline,
  FillinOutline
} from 'antd-mobile-icons';
import './return.css';

/**
 * 菜单项数据类型定义
 * 用于规范帮助菜单中每个选项的数据结构
 */
interface MenuItem {
  id: number;          // 菜单项唯一标识
  text: string;        // 显示文本
  icon: JSX.Element;   // 图标组件
  route?: string;      // 可选 - 内部路由路径
  link?: string;       // 可选 - 外部链接URL
  onClick?: () => void;// 可选 - 点击回调函数
}

/**
 * 新手引导弹窗组件
 * 显示6个引导选项的网格布局弹窗
 */
const NewbieGuide: React.FC<{ visible: boolean; onClose: () => void }> = ({ visible, onClose }) => {
  const popupRef = useRef<HTMLDivElement>(null); // 弹窗DOM引用
  const navigate = useNavigate();                // 路由导航钩子

  /**
   * 处理引导项点击事件
   * @param index 被点击项的索引
   */
  const handleGuideItemClick = (index: number) => {
    // 根据索引执行不同的导航逻辑
    switch (index) {
      case 0: // 新手入门必读
        window.open('https://www.gaoding.com/help-center/article/18569', '_blank');
        break;
      case 1: // 我想直接做一张图
        navigate('/templates');
        break;
      case 2: // 多人共享协作
        window.open('https://www.gaoding.com/dam/teams/263729380', '_blank');
        break;
      case 3: // PSD转在线模板
        window.open('https://www.gaoding.com/help-center/article/1557566945484808192', '_blank');
        break;
      case 4: // 版权知识科普
        window.open('https://www.gaoding.com/help-center/article/1552639847560536064', '_blank');
        break;
      case 5: // 管理者后台
        navigate('/admin/orgs');
        break;
      default:
        console.warn('未知的引导项索引:', index);
    }
    onClose(); // 关闭弹窗
  };

  // 引导项配置数据
  const guideItems = [
    { title: '新手入门必读', content: '创建你的第一个设计', icon: '📚' },
    { title: '我想直接做一张图', content: '海量正版图片与原创模板内容', icon: '🎨' },
    { title: '多人共享协作', content: '与团队共享内容，文件规范存放，多人协同编辑', icon: '👥' },
    { title: 'PSD转在线模板', content: '上传PSD/AI等源文件，生成可复用的在线模板', icon: '🔄' },
    { title: '版权知识科普', content: '了解商用授权，规避侵权风险，创作更无忧', icon: '©️' },
    { title: '管理者后台', content: '成员管理 | 开票 | 内容管理 | 合规控制 | 企业设置', icon: '⚙️' }
  ];

  /**
   * 处理点击弹窗外部关闭
   */
  useEffect(() => {
    if (!visible) return;

    const handleClickOutside = (event: MouseEvent) => {
      if (popupRef.current && !popupRef.current.contains(event.target as Node)) {
        onClose();
      }
    };

    document.addEventListener('mousedown', handleClickOutside);
    return () => document.removeEventListener('mousedown', handleClickOutside);
  }, [visible, onClose]);

  if (!visible) return null; // 不可见时不渲染

  return (
    <div 
      ref={popupRef}
      className="guide-popup"
      role="dialog"
      aria-modal="true"
      aria-labelledby="guide-title"
    >
      <h2 id="guide-title" className="guide-title">轻松搞定协同设计</h2>
      <div className="guide-grid">
        {guideItems.map((item, index) => (
          <div
            key={index}
            className="guide-item"
            onClick={() => handleGuideItemClick(index)}
            role="button"
            tabIndex={0}
            onKeyDown={(e) => e.key === 'Enter' && handleGuideItemClick(index)}
            aria-label={`查看${item.title}指南`}
          >
            <div className="guide-icon">{item.icon}</div>
            <h3>{item.title}</h3>
            <p>{item.content}</p>
          </div>
        ))}
      </div>
    </div>
  );
};

/**
 * 返回顶部和帮助菜单主组件
 * 主要功能：
 * 1. 滚动显示返回顶部按钮
 * 2. 提供帮助菜单和新手引导
 * 3. 支持内部路由和外部链接跳转
 */
const ReturnTop: React.FC = () => {
  const navigate = useNavigate();
  
  // 组件状态管理
  const [showButton, setShowButton] = useState(false);      // 返回顶部按钮显示状态
  const [showHelpPopup, setShowHelpPopup] = useState(false); // 帮助弹窗显示状态
  const [isPopupAnimating, setIsPopupAnimating] = useState(false); // 弹窗动画状态
  const [showGuide, setShowGuide] = useState(false);       // 新手引导弹窗显示状态

  // DOM引用
  const helpAreaRef = useRef<HTMLDivElement>(null);  // 帮助按钮区域引用
  const popupRef = useRef<HTMLDivElement>(null);     // 弹窗区域引用

  // 帮助菜单项配置
  const menuItems: MenuItem[] = [
    { id: 1, text: '人工客服', icon: <UserContactOutline />, route: '/sety' },
    { id: 2, text: '帮助中心', icon: <QuestionCircleOutline />, link: 'https://www.gaoding.com/help-center' },
    { id: 3, text: '建议意见', icon: <MailOutline />, link: 'https://support.qq.com/product/161838' },
    { 
      id: 4, 
      text: '新手引导', 
      icon: <FileOutline />,
      onClick: () => {
        setShowGuide(true);
        setShowHelpPopup(false);
      }
    },
    { id: 5, text: '更新日志', icon: <ContentOutline />, link: 'https://www.gaoding.com/release' },
    { id: 6, text: '提模版需求', icon: <FillinOutline />, link: 'https://gaoding.wjx.cn/vj/Q1AEX2p.aspx' }
  ];

  /**
   * 监听页面滚动事件
   * 滚动超过300px时显示返回顶部按钮
   */
  useEffect(() => {
    const handleScroll = () => {
      setShowButton(window.scrollY > 300);
    };
    window.addEventListener('scroll', handleScroll);
    return () => window.removeEventListener('scroll', handleScroll);
  }, []);

  /**
   * 平滑滚动到页面顶部
   */
  const scrollToTop = () => {
    window.scrollTo({ 
      top: 0, 
      behavior: 'smooth' // 平滑滚动效果
    });
  };

  /**
   * 处理菜单项点击
   * @param item 被点击的菜单项
   */
  const handleMenuItemClick = (item: MenuItem) => {
    if (item.onClick) {
      item.onClick();
    } else if (item.route) {
      navigate(item.route);
    } else if (item.link) {
      window.open(item.link, '_blank', 'noopener,noreferrer');
    }
    closePopup();
  };

  /**
   * 打开帮助弹窗（带动画）
   */
  const openPopup = () => {
    setIsPopupAnimating(true);
    setShowHelpPopup(true);
    setShowGuide(false);
    setTimeout(() => setIsPopupAnimating(false), 100);
  };

  /**
   * 关闭帮助弹窗（带动画）
   */
  const closePopup = () => {
    setIsPopupAnimating(true);
    setTimeout(() => {
      setShowHelpPopup(false);
      setIsPopupAnimating(false);
    }, 100);
  };

  /**
   * 全局鼠标移动检测
   * 当鼠标移出帮助按钮和弹窗区域时关闭弹窗
   */
  useEffect(() => {
    const handleMouseMove = (e: MouseEvent) => {
      if (!showHelpPopup || !helpAreaRef.current || !popupRef.current) return;

      const buttonRect = helpAreaRef.current.getBoundingClientRect();
      const popupRect = popupRef.current.getBoundingClientRect();
      
      // 判断鼠标是否在按钮和弹窗区域外
      const isOutside = 
        e.clientX < Math.min(buttonRect.left, popupRect.left) - 10 ||
        e.clientX > Math.max(buttonRect.right, popupRect.right) + 10 ||
        e.clientY < Math.min(buttonRect.top, popupRect.top) - 10 ||
        e.clientY > Math.max(buttonRect.bottom, popupRect.bottom) + 10;

      if (isOutside) closePopup();
    };

    if (showHelpPopup) {
      document.addEventListener('mousemove', handleMouseMove);
    }

    return () => {
      document.removeEventListener('mousemove', handleMouseMove);
    };
  }, [showHelpPopup]);

  return (
    <div className="page-container">
      {/* 返回顶部按钮 */}
      <button 
        className={`return-top-btn ${showButton ? 'show' : ''}`}
        onClick={scrollToTop}
        aria-label="返回顶部"
      >
        ↑
      </button>

      {/* 帮助按钮区域 */}
      <div className="help-btn-container" ref={helpAreaRef}>
        {/* 帮助按钮 */}
        <button
          className="help-btn"
          onMouseEnter={openPopup}
          aria-label="打开帮助菜单"
        >
          ?
        </button>

        {/* 帮助弹窗 */}
        {(showHelpPopup || isPopupAnimating) && !showGuide && (
          <div 
            className={`help-popup ${isPopupAnimating ? 'animating' : ''}`}
            ref={popupRef}
            onMouseLeave={() => !isPopupAnimating && closePopup()}
          >
            {menuItems.map(item => (
              <div
                key={item.id}
                className="menu-item"
                onClick={() => handleMenuItemClick(item)}
                aria-label={item.text}
              >
                <span className="menu-icon">{item.icon}</span>
                <span className="menu-text">{item.text}</span>
              </div>
            ))}
          </div>
        )}

        {/* 新手引导弹窗 */}
        {showGuide && <NewbieGuide visible={showGuide} onClose={() => setShowGuide(false)} />}
      </div>
    </div>
  );
};

export default ReturnTop;